package com.example.sx_06.suxuantv

import android.app.Activity
import android.app.Instrumentation
import android.inputmethodservice.Keyboard
import android.os.Bundle
import android.os.Handler
import android.view.KeyEvent
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.RelativeLayout
import android.widget.SeekBar
import android.widget.TextView
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.sx_06.suxuantv.cookie.CookieUtil
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import kotlinx.android.synthetic.main.activity_main.*
import android.view.MotionEvent
import android.widget.Toast
import java.io.IOException


class MainActivity : Activity() {

    lateinit var preweb: AgentWeb.PreAgentWeb

    lateinit var mAgentWeb: AgentWeb

    /**
     * adb 常用模拟事件
     *  adb shell input keyevent 23
     *
     *26 -->  KEYCODE_POWER 电源键
     *3 -->  "KEYCODE_HOME" 桌面
     * 4 -->  "KEYCODE_BACK" 返回
     * 1 -->  "KEYCODE_MENU" 菜单
     * 19 -->  "KEYCODE_DPAD_UP" 上
     *20 -->  "KEYCODE_DPAD_DOWN" 下
     *21 -->  "KEYCODE_DPAD_LEFT" 左
     *22 -->  "KEYCODE_DPAD_RIGHT" 右
     *23 -->  "KEYCODE_DPAD_CENTER" ok
     *66 -->  "KEYCODE_ENTER"  ok
     *24 -->  "KEYCODE_VOLUME_UP"  声音+
     *25 -->  "KEYCODE_VOLUME_DOWN" 声音-
     * */
    //webview 使用：https://github.com/Justson/AgentWeb
    //安卓按键对应
    //https://blog.csdn.net/callinghl/article/details/17218003
    //小米tv 开发者
    //https://dev.mi.com/console/doc/detail?pId=73
    var url = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val erroView = TextView(this)
        erroView.setText("加载失败点击刷新！")
        val view = layoutInflater.inflate(R.layout.activity_main, null, false)
        setContentView(view)
        url = Contact.getFullUrl(Contact.sunbeibei)


        //   synchronousWebCookies(this, Contact.CRM, cookie)
        val webview = CustomWebView(this);
        webview.setInitialScale(110)
        val settings = CustomSettings()
        preweb = AgentWeb.with(this)
                .setAgentWebParent(root_View as RelativeLayout, RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(object : WebChromeClient() {
                    override fun onProgressChanged(view: WebView?, newProgress: Int) {
                        LogUtils.d(view?.url+"网页进度"+newProgress)
                        super.onProgressChanged(view, newProgress)
                    }
                }).setWebViewClient(object : WebViewClient() {
                    override fun shouldOverrideKeyEvent(view: WebView?, event: KeyEvent?): Boolean {
                        // ToastUtils.showShort(event?.keyCode.toString())
                        return super.shouldOverrideKeyEvent(view, event)
                    }
                }).setMainFrameErrorView(erroView)
                .setAgentWebWebSettings(settings)
                //设置 IAgentWebSettings。
                .createAgentWeb().ready()
        ///url="http://www.jd.com"
        LogUtils.d("数据：$url")
        //同步cookie
        val cookie = CookieUtil.cookiesString(Contact.CRM, "/")
        //4.3版本的系统需要先初始化后才能同步
        //        AgentWebConfig.removeAllCookies();
        AgentWebConfig.syncCookie(url, cookie)

        val cookies = CookieUtil.cookies(Contact.CRM, "/")
        cookies.forEach {
            AgentWebConfig.syncCookie(url, "${it.name()}=${it.value()};path=${it.path()};domain=${it.domain()}")
        }
        LogUtils.d("cookie： ${AgentWebConfig.getCookiesByUrl(url)}")
        mAgentWeb = preweb.go(url)
        pro.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onStartTrackingTouch(p0: SeekBar?) {
                // ToastUtils.showShort("onStartTrackingTouch${p0.toString()}")
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                // ToastUtils.showShort("onStopTrackingTouch${p0.toString()}")
            }

            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                webview.setInitialScale(100 + p1)
                mAgentWeb.webCreator.webView.setInitialScale(100 + p1)
                //  ToastUtils.showShort("onProgressChanged${p0.toString()}${p1.toString()}${p2.toString()}")
            }
        })
        pro_text_size.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onStartTrackingTouch(p0: SeekBar?) {
                // ToastUtils.showShort("onStartTrackingTouch${p0.toString()}")
            }

            override fun onStopTrackingTouch(p0: SeekBar?) {
                // ToastUtils.showShort("onStopTrackingTouch${p0.toString()}")
            }

            override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
                settings.toSetting(webview).webSettings.defaultFontSize = p1
                //  ToastUtils.showShort("onProgressChanged${p0.toString()}${p1.toString()}${p2.toString()}")
            }
        })
//        ToastUtils.showShort(currentFocus.javaClass.name)
        ///     pro_text_size.requestFocus()
        mAgentWeb.webCreator.webView.isFocusable = true
        mAgentWeb.webCreator.webView.isFocusableInTouchMode = true
        mAgentWeb.webCreator.webView.requestFocus()
        mAgentWeb.webCreator.webView.setInitialScale(110)
        initMouseMrg()
        mMouseManager.showMouseView()
    }

    fun simulateKeystroke(KeyCode: Int) {
        Thread {
            run() {
                try {
                    val inst = Instrumentation();
                    inst.sendKeyDownUpSync(KeyCode);
                } catch (e: Exception) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        ToastUtils.showShort(keyCode.toString())




        when (keyCode) {
           80-> {

                Handler().postDelayed (MouseRunable, 100);
            }
            KeyEvent.KEYCODE_ENTER -> {
              //  ToastUtils.showShort(currentFocus.javaClass.name)
                ////   currentFocus.callOnClick()
                //  Toast.makeText(this, "ENTER中间键", Toast.LENGTH_SHORT).show()
            }
            KeyEvent.KEYCODE_DPAD_CENTER -> {
                //Toast.makeText(this, "DPAD_CENTER中间键", Toast.LENGTH_SHORT).show()
            //    ToastUtils.showShort(currentFocus.javaClass.name)
            }

            KeyEvent.KEYCODE_MENU -> {
                //Toast.makeText(this, "KEYCODE_MENU菜单  ", Toast.LENGTH_SHORT).show()
                if (ll_status.visibility == View.VISIBLE) {
                    mAgentWeb.webCreator.webView.requestFocus()
                    ll_status.visibility = View.GONE

                } else {
                    pro.requestFocus()
                    ll_status.visibility = View.VISIBLE
                }
               // ToastUtils.showShort(currentFocus.javaClass.name)
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    override fun onPause() {
        mAgentWeb.getWebLifeCycle().onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb.getWebLifeCycle().onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy()
        super.onDestroy()
    }

    lateinit var mMouseManager: TcMouseManager
    fun initMouseMrg() {
        mMouseManager = TcMouseManager()
        mMouseManager.init(root_View, TcMouseManager.MOUSE_TYPE)
        mMouseManager.setShowMouse(true)
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        return if (mMouseManager != null && mMouseManager.isShowMouse) {
            if (event.keyCode == KeyEvent.KEYCODE_DPAD_CENTER||event.keyCode == KeyEvent.KEYCODE_ENTER) {
                setMouseClick()
                return true
            } else {

                //     * 19 -->  "KEYCODE_DPAD_UP" 上
                //     *20 -->  "KEYCODE_DPAD_DOWN" 下
                //     *21 -->  "KEYCODE_DPAD_LEFT" 左
                //     *22 -->  "KEYCODE_DPAD_RIGHT" 右
                if (event.keyCode==KeyEvent.KEYCODE_DPAD_UP||event.keyCode==KeyEvent.KEYCODE_DPAD_DOWN||
                      event.keyCode==KeyEvent.KEYCODE_DPAD_RIGHT  ||
                        event.keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
                    mMouseManager.onDpadClicked(event)
                }else{
                    super.dispatchKeyEvent(event)
                }

            }
        } else super.dispatchKeyEvent(event)
    }

    // 模拟屏幕点击事件
    fun setMouseClick() {
        val evenDownt = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis() + 100,
                MotionEvent.ACTION_DOWN, mMouseManager.mMouseView.mMouseView.x+5, mMouseManager.mMouseView.mMouseView.y, 0)
        dispatchTouchEvent(evenDownt)
        val eventUp = MotionEvent.obtain(System.currentTimeMillis(), System.currentTimeMillis() + 100, MotionEvent.ACTION_UP,
                mMouseManager.mMouseView.mMouseView.x+5, mMouseManager.mMouseView.mMouseView.y, 0)
        dispatchTouchEvent(eventUp)
        evenDownt.recycle()
        eventUp.recycle()
    }

    // 模拟键盘按键，Keycode对应Android键盘按键的的keycode
    fun setKeyPress(keycode: Int) {
        val i = Instrumentation()
        try {
            val keyCommand = "input keyevent $keycode"
            val runtime = Runtime.getRuntime()
            val proc = runtime.exec(keyCommand)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


}

internal var MouseRunable: Runnable = Runnable {

   //val mstate =    System.getProperties().get("sys.KeyMouse.mKeyMouseState")
    val mstate =   getProperty("sys.KeyMouse.mKeyMouseState","off")
    LogUtils.d("当前鼠标:$mstate")
    if (mstate.equals("on")) {
        System.getProperties().set("sys.KeyMouse.mKeyMouseState", "off")
        setProperty("sys.KeyMouse.mKeyMouseState", "off")
        //SystemProperties.set("sys.KeyMouse.mKeyMouseState", "off")
   //     Toast.makeText(mContext, "Diable mouse mode.", Toast.LENGTH_LONG).show()
    } else {
//        System.getProperties().set("sys.KeyMouse.mKeyMouseState", "on")
        System.getProperties().set("sys.KeyMouse.mKeyMouseState", "on")
        setProperty("sys.KeyMouse.mKeyMouseState", "on")
   //     Toast.makeText(mContext, "Enable mouse mode,long press again to disable.", Toast.LENGTH_LONG).show()
    }





}
fun getProperty(key: String, defaultValue: String): String {
    var value = defaultValue
    try {
        val c = Class.forName("android.os.SystemProperties")
        val get = c.getMethod("get", String::class.java, String::class.java)
        value = get.invoke(c, key, "unknown") as String
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        return value
    }
}

fun setProperty(key: String, value: String) {
    try {
        val c = Class.forName("android.os.SystemProperties")
        val set = c.getMethod("set", String::class.java, String::class.java)
        set.invoke(c, key, value)
    } catch (e: Exception) {
        e.printStackTrace()
    }

}
